<template>
  <div>
    <el-dialog
      v-bind="$attrs"
      v-on="$listeners"
      append-to-body
      :title="isDisabled ? '附件查看/下载' : title"
      :width="downLoad ? '30%' : '40%'"
    >
      <el-upload
        :action="baseUrl" 
        ref="upload"
        :headers="{ Authorization: $store.getters.token }"
        :file-list="fileList"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :show-file-list="false"
        :multiple="true"
        :limit="9"
        :http-request="uploadFile"
        :on-exceed="handleExceed"
        :accept="accept"
        :before-upload="beforeUpload"
        :disabled="isDisabled"
        :on-change="handleChange"
        :auto-upload="false"
      >
        <div v-if="!downLoad && !isDisabled">
          <div slot="tip" class="el-upload__tip">
            <el-button
              size="small"
              icon="el-icon-upload"
              style="
                margin-bottom: 10px;
                font-size: 18px;
                border: 1px dashed rgba(245, 247, 250);
                color: skyblue;
              "
              >选择文件</el-button
            >
            &nbsp; &nbsp;{{
              isDisabled? "": "只能上传不超过的" +  fileSize +sizeUnit + `的文件`
            }}
              <!-- isDisabled? "": "只能上传不超过的" +  fileSize +sizeUnit + `${invoice==false?'的.xls, .xlsx, .docx, .zip, .pdf 文件':'的文件'}` -->

          </div>
        </div>
      </el-upload>
      <template v-if="fileList.length">
        <p
          class="el-upload-list__item is-success"
          v-for="(file, index) in fileList"
          :key="file.fileId"
        >
          <a class="el-upload-list__item-name" @click="handleClick(file)">
            <i class="el-icon-document"></i>{{ file.name }}
          </a>
          <label
            v-if="file.url && !isDisabled"
            class="el-upload-list__item-status-label"
          >
            <i class="el-icon-upload-success el-icon-circle-check"></i>
          </label>
          <i
            v-if="!downLoad && !isDisabled"
            class="el-icon-close"
            @click="handleRemove(file, index)"
          ></i>
        </p>
      </template>
      <span slot="footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button
          @click="submit"
          v-if="!isDisabled && !isUpload"
          type="success"
          >上传</el-button
        >
        <el-button
          type="primary"
          v-if="!isDisabled && fileList.length && isUpload"
          @click="saveFile"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDownloadUrl } from "@/api/common";
import request from "@/utils/request";
const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024,
};
export default {
  props: {
    // 是否查看禁用
    isDisabled: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "上传/下载附件",
    },
    // 是否禁止上传只可以下载/有删除操作
    downLoad: {
      type: Boolean,
      default: false,
    },
    // 文件列表
    value: {
      default: () => [],
    },
    accept: {
      type: String,
      default: "*",
    },
    type: {
      type: String,
      default: "annex",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    sizeUnit: {
      type: String,
      default: "MB",
    },
    index: {
      type: String,
    },
    fileSize: {
      type: Number,
      default: 2,
    },
    // 是否是发票附件上传
    invoice:{
      type: Boolean,
      default: false,
    },
  },
  name: "",
  data() {
    return {
      fileData: "",
      fileList: [],
      uploadData: {
        fieldData: {
          id: "", // 机构id,
        },
      },
      baseUrl: `${this.define.comUploadUrl}/upload`,
      isUpload: "",
      size_: 0, //判断是否有新文件
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (typeof val == "string" && val) {
          this.fileList = JSON.parse(val);
        } else if (Array.isArray(val)) {
          this.fileList = val;
        } else {
          this.fileList = [];
        }
      },
    },
  },
  created() {},
  methods: {
    saveFile() {
      this.$emit("update:visible", false);
      this.$emit("input", JSON.stringify(this.fileList));
    },
    // 上传文件
    uploadFile(file) {
      this.fileData.append("file", file.file); // append增加数据
      this.size_ = 1;
    },
    //监控上传文件列表
    handleChange(file, fileList) {
      this.isUpload = false;
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
    },
    submit() {
      if (!this.fileList.length) {
        this.$message({
          message: "请先选择文件",
          type: "warning",
        });
      } else {
        const unitNum = units[this.sizeUnit];
        let currentUpload = this.fileList.filter((item) => item.size);
        const isLt100M = currentUpload.every(
          (file) => file.size / unitNum < this.fileSize
        );
        if (!isLt100M) {
          this.$message.error(
            `请检查，上传文件大小不能超过${this.fileSize}MB!`
          );
          this.fileList.forEach((item, index) => {
            if (item.size / 1024 / 1024 > this.fileSize) {
              this.fileList.splice(index, 1);
            }
          });
        } else {
          this.fileData = "";
          this.size_ = 0;
          this.fileData = new FormData(); // new formData对象
          this.$refs.upload.submit(); // 提交调用uploadFile函数
          // !this.size_ && this.$message.warning("请先选择新文件");
          this.isUpload = true;
          this.size_ &&
            request({
              url: this.define.comUploadUrl + "/upload",
              method: "post",
              data: this.fileData,
              headers: { Authorization: this.$store.getters.token },
            }).then((res) => {
              if (res.code == 200) {
                this.$message({
                  message: "上传成功",
                  type: "success",
                  duration: 1000,
                  onClose: () => (this.isUpload = true),
                });

                this.fileList.forEach((item, index) => {
                  res.data.forEach((item1) => {
                    if (item.name == item1.name) {
                      this.$set(this.fileList, index, {
                        name: item1.name,
                        fileId: item1.fileId,
                        url: item1.ossAddress,
                      });
                    }
                  });
                });
                this.$emit("input", this.fileList);
              } else {
                this.$message({
                  message: res.data.desc,
                  type: "error",
                });
              }
            });
        }
      }
    },
    beforeUpload(file) {
      let isRightSize = file.size / (1024 * 1024) < 500;
      if (!isRightSize) this.$message.error(`文件大小不能超过500MB`);
      return isRightSize;
    },
    handleRemove(file, index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.fileList);
      // this.$confirm(`确定移除${file.name}？`, '提示').then(() => {
      // }).catch(() => { })
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).catch(() => {});
    },
    handleClick(file) {
      // 点击下载文件
      if (!file.fileId) return;
      window.location.href = file.url;
    },
    handleExceed() {
      this.$message.warning(`当前限制最多可以上传9个文件`);
    },
  },
};
</script>

<style lang='scss' scoped>
>>> .el-dialog__body {
  padding: 0 20px 10px 20px;
  max-height: 300px;
  overflow-y: auto;
}
</style>